package com.gufe.service.user.impl.mp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gufe.constant.JwtClaimsConstant;
import com.gufe.dto.UserLoginDTO;
import com.gufe.entity.User;
import com.gufe.exception.LoginFailedException;
import com.gufe.mapper.user.mp.UserMapper;
import com.gufe.properties.JwtProperties;
import com.gufe.properties.WeChatProperties;
import com.gufe.service.user.mp.UserService;
import com.gufe.utils.JwtUtil;
import com.gufe.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import utils.HttpClientUtil;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    JwtProperties jwtProperties;

    @Autowired
    private WeChatProperties weChatProperties;

    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Override
    public UserLoginVO wxlogin(UserLoginDTO userLoginDTO) {
        // 获取openid
        String openid = getOpenId(userLoginDTO.getCode());
        log.info("获取到的openid为：{}", openid);

        // 判断openid是否为空
        if (openid == null || openid.isEmpty()) {
            log.error("获取openid失败");
            throw new LoginFailedException("获取openid失败");
        }

        // 查询用户
        User user = userMapper.getByOpenId(openid);

        // 新用户自动注册
        if (user == null) {
            log.info("新用户注册，openid：{}", openid);
            user = User.builder()
                    .status(1)
                    .openId(openid)
                    .username("19029")  // 设置默认值
                    .name("用户coco,")
                    .avatarUrl("https://dragonweb-bucket.oss-cn-beijing.aliyuncs.com/8dcc950f-e4fe-4232-9625-ef34bb7a8de1.jpg")// 设置默认值
                    .build();

            userMapper.insertUser(user);
            log.info("新用户注册成功，id：{}", user.getId());
        }

        //生成jwt
        Map<String, Object> Claims = new HashMap<>();
        Claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                user.getName(),
                Claims);

        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setToken(token);
        userLoginVO.setUserId(Long.valueOf(user.getId()));
        if(user.getAvatarUrl() != null && !user.getAvatarUrl().isEmpty()) {
            userLoginVO.setAvatarUrl(user.getAvatarUrl());
        }
        if(user.getGender() != null) {
            userLoginVO.setGender(user.getGender().toString());
        }
        if(user.getName() != null && !user.getName().isEmpty()) {
            userLoginVO.setName(user.getName());
        }

        return userLoginVO;
    }

    private String getOpenId(String code) {
        try {
            // 封装请求参数
            Map<String, String> map = new HashMap<>();
            map.put("appid", weChatProperties.getAppid());
            map.put("secret", weChatProperties.getSecret());
            map.put("js_code", code);
            map.put("grant_type", "authorization_code");

            // 发送请求
            String json = HttpClientUtil.doGet(WX_LOGIN, map);
            log.info("微信登录响应：{}", json);

            // 解析响应
            JSONObject jsonObject = JSON.parseObject(json);

            // 判断是否有错误
            if (jsonObject.containsKey("errcode") && jsonObject.getInteger("errcode") != 0) {
                log.error("微信登录请求失败：{}", jsonObject.getString("errmsg"));
                return null;
            }

            return jsonObject.getString("openid");
        } catch (Exception e) {
            log.error("获取openid失败：", e);
            return null;
        }
    }
}
